package mobilesearch.thread;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import java.util.ArrayList;
import mobilesearch.data.BookmarkData;
import mobilesearch.ui.BroadcastCommand;
import android.database.Cursor;
import android.provider.Browser;
import android.content.ContentProvider;

public class BookmarkSearchThread extends Thread {

	private static final String TAG = "BookmarkSearchThread";
	private ContentResolver resolver;
	private Context context;
	
	private String title;
	private String url;
	
	public BookmarkSearchThread(Context context, ContentResolver resolver) {
		super();
		this.context = context;
		this.resolver = resolver;
	}

	@Override
	public void run() {
		super.run();
		Log.i(TAG, "run()");
		
		ArrayList<BookmarkData> bookmarkList = new ArrayList<BookmarkData>();
		
		try{
			Cursor cursor = this.resolver.query(Browser.BOOKMARKS_URI, null, null, null, null);
			if(cursor.moveToFirst()){
				Log.i(TAG, "cursor.moveToFirst()");
				do{
					BookmarkData data = new BookmarkData();
					
					int titleIndex = cursor.getColumnIndex(Browser.BookmarkColumns.TITLE);
					this.title = cursor.getString(titleIndex);
					
					int bookmarkIndex = cursor.getColumnIndex(Browser.BookmarkColumns.URL);
					this.url = cursor.getString(bookmarkIndex);
					
					data.setTitle(this.title);
					data.setUrl(this.url);
					
					bookmarkList.add(data);
				}while(cursor.moveToNext());
			}
		}catch(Exception exception){
			Log.i(TAG, exception.toString());
		}
		
		//broadcast the data to the activity
		if(!bookmarkList.isEmpty()){
			Intent bookmarkIntent = new Intent(BroadcastCommand.SEARCH_BOOKMARK);
			bookmarkIntent.putParcelableArrayListExtra(BroadcastCommand.SEARCH_BOOKMARK, bookmarkList);
			this.context.sendBroadcast(bookmarkIntent);	
		}
		
	}
}
